<template>
	<view class="container">
		<!-- 头部导航 -->
		<CustomNavbar title="全部记录" :showBack="true" />
		
		<!-- 筛选条件 -->
		<view class="filter-section">
			<view class="filter-tabs">
				<view 
					:class="['filter-tab', filterType === 'all' ? 'active' : '']"
					@click="setFilterType('all')"
				>
					全部
				</view>
				<view 
					:class="['filter-tab', filterType === 'expense' ? 'active' : '']"
					@click="setFilterType('expense')"
				>
					支出
				</view>
				<view 
					:class="['filter-tab', filterType === 'income' ? 'active' : '']"
					@click="setFilterType('income')"
				>
					收入
				</view>
			</view>
			
			<!-- 月份选择 -->
			<view class="month-selector">
				<view class="month-nav" @click="changeMonth(-1)">
					<text class="nav-arrow">‹</text>
				</view>
				<view class="month-display">
					<text class="month-text">{{currentYear}}年{{currentMonth}}月</text>
				</view>
				<view class="month-nav" @click="changeMonth(1)">
					<text class="nav-arrow">›</text>
				</view>
			</view>
		</view>
		
		<!-- 统计概览 -->
		<view class="summary-section">
			<view class="summary-item expense">
				<text class="summary-label">支出</text>
				<text class="summary-amount">¥{{totalExpense}}</text>
			</view>
			<view class="summary-item income">
				<text class="summary-label">收入</text>
				<text class="summary-amount">¥{{totalIncome}}</text>
			</view>
			<view class="summary-item balance">
				<text class="summary-label">结余</text>
				<text class="summary-amount">¥{{totalBalance}}</text>
			</view>
		</view>
		
		<!-- 记录列表 -->
		<view class="records-section">
			<scroll-view 
				class="records-scroll" 
				scroll-y 
				@scrolltolower="loadMore"
			>
				<!-- 按日期分组的记录 -->
				<view v-for="(group, date) in groupedRecords" :key="date" class="date-group">
					<view class="date-header">
						<text class="date-text">{{formatDateHeader(date)}}</text>
						<text class="date-total">{{getDayTotal(group)}}</text>
					</view>
					
					<view class="records-list">
						<view 
							v-for="record in group" 
							:key="record.id" 
							class="record-item"
							@click="editRecord(record)"
						>
							<view class="record-icon">
								<text class="icon-text">{{getCategoryIcon(record.category, record.type)}}</text>
							</view>
							<view class="record-info">
								<text class="record-category">{{record.category}}</text>
								<view class="record-details">
									<text class="record-note">{{record.note || '无备注'}}</text>
									<view class="account-info">
										<text class="account-icon">{{record.accountIcon || (record.accountId ? '💳' : '📝')}}</text>
										<text class="account-name">{{record.accountName || (record.accountId ? '未知账户' : '不计入账户')}}</text>
									</view>
								</view>
							</view>
							<view class="record-amount">
								<text :class="['amount-text', record.type === 'expense' ? 'expense' : 'income']">
									{{record.type === 'expense' ? '-' : '+'}}¥{{record.amount}}
								</text>
								<text class="record-time">{{formatTime(record.date)}}</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-if="records.length === 0 && !loading" class="empty-state">
					<view class="empty-cat">
						<view class="cat-face">
							<view class="cat-ears">
								<view class="ear left"></view>
								<view class="ear right"></view>
							</view>
							<view class="cat-eyes">
								<view class="eye left"></view>
								<view class="eye right"></view>
							</view>
							<view class="cat-nose"></view>
						</view>
					</view>
					<text class="empty-text">暂无记录</text>
					<text class="empty-desc">点击右下角按钮开始记账吧~</text>
				</view>
				
				<!-- 加载更多 -->
				<view v-if="loading" class="loading-more">
					<text class="loading-text">加载中...</text>
				</view>
				
				<view v-if="!hasMore && records.length > 0" class="no-more">
					<text class="no-more-text">没有更多记录了</text>
				</view>
			</scroll-view>
		</view>
		
		<!-- 悬浮添加按钮 -->
		<view class="fab" @click="showAddModal">
			<text class="fab-icon">+</text>
		</view>
		
		<!-- 记账弹窗组件 -->
		<AddRecordModal 
			:visible="modalVisible"
			:editRecord="editRecordData"
			@close="hideAddModal"
			@save-success="onRecordSaved"
			@delete-success="onRecordDeleted"
		/>
	</view>
</template>

<script>
	import { recordAPI, categoryAPI, apiUtils } from '@/utils/api.js'
	import AddRecordModal from '@/components/AddRecordModal.vue'
	import CustomNavbar from '@/components/CustomNavbar.vue'
	
	export default {
		components: {
			AddRecordModal,
			CustomNavbar
		},
		data() {
			return {
				currentYear: new Date().getFullYear(),
				currentMonth: new Date().getMonth() + 1,
				filterType: 'all', // all, expense, income
				records: [],
				expenseCategories: [],
				incomeCategories: [],
				loading: false,
				hasMore: true,
				page: 1,
				pageSize: 20,
				modalVisible: false,
				editRecordData: null
			}
		},
		computed: {
			filteredRecords() {
				if (this.filterType === 'all') {
					return this.records
				}
				return this.records.filter(record => record.type === this.filterType)
			},
			groupedRecords() {
				const groups = {}
				this.filteredRecords.forEach(record => {
					const date = record.date.split(' ')[0] // 取日期部分
					if (!groups[date]) {
						groups[date] = []
					}
					groups[date].push(record)
				})
				
				// 按日期降序排序
				const sortedGroups = {}
				Object.keys(groups)
					.sort((a, b) => new Date(b) - new Date(a))
					.forEach(key => {
						sortedGroups[key] = groups[key].sort((a, b) => 
							new Date(b.date) - new Date(a.date)
						)
					})
				
				return sortedGroups
			},
			totalExpense() {
				return this.filteredRecords
					.filter(record => record.type === 'expense')
					.reduce((sum, record) => sum + parseFloat(record.amount), 0)
					.toFixed(2)
			},
			totalIncome() {
				return this.filteredRecords
					.filter(record => record.type === 'income')
					.reduce((sum, record) => sum + parseFloat(record.amount), 0)
					.toFixed(2)
			},
			totalBalance() {
				return (parseFloat(this.totalIncome) - parseFloat(this.totalExpense)).toFixed(2)
			}
		},
		onLoad() {
			// 检查登录状态
			if (!apiUtils.isLoggedIn()) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
				return;
			}
			this.loadCategories()
			this.loadRecords()
		},
		onPullDownRefresh() {
			this.onRefresh()
		},
		methods: {
			async loadCategories() {
				try {
					// 获取支出分类
					const expenseCategories = await categoryAPI.getByType('EXPENSE')
					this.expenseCategories = expenseCategories.map(cat => ({
						id: cat.id,
						name: cat.name,
						icon: this.getIconEmoji(cat.icon)
					}))
					
					// 获取收入分类
					const incomeCategories = await categoryAPI.getByType('INCOME')
					this.incomeCategories = incomeCategories.map(cat => ({
						id: cat.id,
						name: cat.name,
						icon: this.getIconEmoji(cat.icon)
					}))
				} catch (error) {
					console.error('加载分类失败:', error)
				}
			},
			getIconEmoji(iconName) {
				// 图标名称到emoji的映射
				const iconMap = {
					// 收入分类
					'money': '💰',
					'gift': '🎁',
					'trending-up': '📈',
					'briefcase': '💼',
					'bar-chart': '📊',
					
					// 支出分类
					'restaurant': '🍽️',
					'car': '🚗',
					'shopping-cart': '🛒',
					'gamepad': '🎮',
					'medical': '🏥',
					'book': '📚',
					'home': '🏠',
					'list': '📝'
				}
				
				return iconMap[iconName] || '📝' // 默认图标
			},
			async loadRecords(append = false) {
				if (this.loading) return
				
				try {
					this.loading = true
					
					// 获取当前月份的日期范围
					const startDate = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-01`
					const endDate = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-${new Date(this.currentYear, this.currentMonth, 0).getDate()}`
					
					console.log('查询日期范围:', startDate, '到', endDate)
					
					// 调用后端API获取记录
					const records = await recordAPI.getByDateRange(startDate, endDate)
					console.log('API返回的记录数据:', records)
					
					if (!records || !Array.isArray(records)) {
						console.warn('API返回的数据格式不正确:', records)
						if (!append) this.records = []
						return
					}
					
					// 处理记录数据
					const processedRecords = records.map(record => {
						const processed = {
							id: record.id,
							type: (record.recordType || record.type || 'expense').toLowerCase(),
							amount: record.amount || 0,
							category: record.category?.name || record.categoryName || '未分类',
							categoryId: record.category?.id || record.categoryId,
							note: record.note || record.description || '',
							date: record.recordDate || record.date || record.createdAt,
							accountName: record.accountName,
							accountIcon: record.accountIcon,
							accountType: record.accountType,
							accountId: record.accountId,
							account: record.account || null
						}
						
						// 调试信息
						console.log('处理记录:', {
							id: processed.id,
							accountId: processed.accountId,
							accountName: processed.accountName,
							originalRecord: record
						})
						
						return processed
					})
					
					if (append) {
						this.records = [...this.records, ...processedRecords]
					} else {
						this.records = processedRecords
					}
					
					// 判断是否还有更多数据
					this.hasMore = records.length >= this.pageSize
					
				} catch (error) {
					console.error('加载记录失败:', error)
					uni.showToast({
						title: '加载失败: ' + error.message,
						icon: 'none'
					})
				} finally {
					this.loading = false
					uni.stopPullDownRefresh()
				}
			},
			setFilterType(type) {
				this.filterType = type
			},
			changeMonth(delta) {
				let newMonth = this.currentMonth + delta
				let newYear = this.currentYear
				
				if (newMonth > 12) {
					newMonth = 1
					newYear++
				} else if (newMonth < 1) {
					newMonth = 12
					newYear--
				}
				
				this.currentMonth = newMonth
				this.currentYear = newYear
				this.page = 1
				this.hasMore = true
				this.loadRecords()
			},
			onRefresh() {
				this.page = 1
				this.hasMore = true
				this.loadRecords()
			},
			loadMore() {
				if (!this.hasMore || this.loading) return
				this.page++
				this.loadRecords(true)
			},
			getCategoryIcon(categoryName, type) {
				// 从已加载的分类中查找图标
				const categoryList = type === 'expense' ? this.expenseCategories : this.incomeCategories
				const category = categoryList.find(cat => cat.name === categoryName)
				return category ? category.icon : '📝'
			},
			formatDateHeader(dateString) {
				const date = new Date(dateString)
				const today = new Date()
				const yesterday = new Date(today)
				yesterday.setDate(yesterday.getDate() - 1)
				
				if (date.toDateString() === today.toDateString()) {
					return '今天'
				} else if (date.toDateString() === yesterday.toDateString()) {
					return '昨天'
				} else {
					return `${date.getMonth() + 1}月${date.getDate()}日`
				}
			},
			formatTime(dateString) {
				const date = new Date(dateString)
				return date.toLocaleTimeString('zh-CN', { 
					hour: '2-digit', 
					minute: '2-digit',
					hour12: false
				})
			},
			getDayTotal(records) {
				const expense = records
					.filter(record => record.type === 'expense')
					.reduce((sum, record) => sum + parseFloat(record.amount), 0)
				const income = records
					.filter(record => record.type === 'income')
					.reduce((sum, record) => sum + parseFloat(record.amount), 0)
				
				if (this.filterType === 'expense') {
					return `支出 ¥${expense.toFixed(2)}`
				} else if (this.filterType === 'income') {
					return `收入 ¥${income.toFixed(2)}`
				} else {
					const balance = income - expense
					return `${balance >= 0 ? '+' : ''}¥${balance.toFixed(2)}`
				}
			},
			showAddModal() {
				this.editRecordData = null
				this.modalVisible = true
			},
			hideAddModal() {
				this.modalVisible = false
				this.editRecordData = null
			},
			editRecord(record) {
				this.editRecordData = record
				this.modalVisible = true
			},
			onRecordSaved() {
				// 记录保存成功后重新加载数据
				this.loadRecords()
			},
			onRecordDeleted() {
				// 记录删除成功后重新加载数据
				this.loadRecords()
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/uni.scss';
	
	.container {
		background: $cute-gradient-bg;
		height: 100vh;
		padding-top: calc(var(--status-bar-height, 44px) + 88rpx);
		box-sizing: border-box;
		display:flex;
		flex-direction: column;
	}
	
	/* 筛选条件 */
	.filter-section {
		background: $cute-bg-secondary;
		margin: 10rpx 20rpx 20rpx 20rpx;
		border-radius: $cute-border-radius;
		padding: 30rpx;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.filter-tabs {
		display: flex;
		background: $cute-bg-tertiary;
		border-radius: $cute-border-radius;
		padding: 6rpx;
		margin-bottom: 30rpx;
	}
	
	.filter-tab {
		flex: 1;
		text-align: center;
		padding: 15rpx 20rpx;
		border-radius: $cute-border-radius;
		font-size: 26rpx;
		color: $cute-text-secondary;
		transition: $cute-transition;
		
		&.active {
			background: $cute-gradient-primary;
			color: $cute-text-inverse;
			box-shadow: $cute-button-shadow;
		}
		
		&:active {
			transform: scale(0.98);
		}
	}
	
	.month-selector {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.month-nav {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: $cute-gradient-accent;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: $cute-transition;
		
		&:active {
			transform: scale(0.9);
		}
	}
	
	.nav-arrow {
		font-size: 32rpx;
		color: $cute-text-inverse;
		font-weight: bold;
	}
	
	.month-display {
		margin: 0 40rpx;
	}
	
	.month-text {
		font-size: 32rpx;
		font-weight: bold;
		color: $cute-text-primary;
	}
	
	/* 统计概览 */
	.summary-section {
		display: flex;
		margin: 0 20rpx 15rpx;
		gap: 15rpx;
	}
	
	.summary-item {
		flex: 1;
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		padding: 25rpx 20rpx;
		text-align: center;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
		
		&.expense {
			border-left: 6rpx solid $cute-error;
		}
		
		&.income {
			border-left: 6rpx solid $cute-success;
		}
		
		&.balance {
			border-left: 6rpx solid $cute-primary;
		}
	}
	
	.summary-label {
		display: block;
		font-size: 24rpx;
		color: $cute-text-secondary;
		margin-bottom: 8rpx;
	}
	
	.summary-amount {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		color: $cute-text-primary;
	}
	
	/* 记录列表 */
	.records-section {
		flex:1;
		height: 0;
		overflow-y:auto;
		margin: 0 20rpx;
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.date-group {
		border-bottom: 2rpx solid $cute-divider;
		
		&:last-child {
			border-bottom: none;
		}
	}
	
	.date-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background: $cute-bg-tertiary;
		border-bottom: 2rpx solid $cute-divider;
	}
	
	.date-text {
		font-size: 28rpx;
		font-weight: bold;
		color: $cute-text-primary;
	}
	
	.date-total {
		font-size: 24rpx;
		color: $cute-text-secondary;
	}
	
	.records-list {
		padding: 0 30rpx;
	}
	
	.record-item {
		display: flex;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 2rpx solid $cute-divider;
		transition: $cute-transition;
		
		&:last-child {
			border-bottom: none;
		}
		
		&:active {
			background: $cute-bg-tertiary;
			border-radius: 20rpx;
			padding: 25rpx 15rpx;
			margin: 0 -15rpx;
			transform: $cute-hover-transform;
		}
	}
	
	.record-icon {
		width: 80rpx;
		height: 80rpx;
		background: $cute-gradient-accent;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 25rpx;
		box-shadow: $cute-button-shadow;
	}
	
	.icon-text {
		font-size: 36rpx;
	}
	
	.record-info {
		flex: 1;
	}
	
	.record-category {
		display: block;
		font-size: 30rpx;
		color: $cute-text-primary;
		margin-bottom: 8rpx;
		font-weight: 500;
	}
	
	.record-details {
		display: flex;
		flex-direction: column;
		margin-top: 5rpx;
	}

	.record-note {
		font-size: 24rpx;
		color: $cute-text-secondary;
		margin-bottom: 3rpx;
	}

	.account-info {
		display: flex;
		align-items: center;
		margin-top: 3rpx;
	}

	.account-icon {
		font-size: 20rpx;
		margin-right: 8rpx;
	}

	.account-name {
		font-size: 22rpx;
		color: $cute-text-tertiary;
		background: $cute-bg-tertiary;
		padding: 2rpx 8rpx;
		border-radius: 8rpx;
	}
	
	.record-amount {
		text-align: right;
	}
	
	.amount-text {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
		
		&.expense {
			color: $cute-error;
		}
		
		&.income {
			color: $cute-success;
		}
	}
	
	.record-time {
		font-size: 22rpx;
		color: $cute-text-tertiary;
	}
	
	/* 空状态 */
	.empty-state {
		padding: 100rpx 50rpx;
		text-align: center;
	}
	
	.empty-cat {
		margin-bottom: 40rpx;
		display: flex;
		justify-content: center;
	}
	
	.cat-face {
		width: 120rpx;
		height: 120rpx;
		background: $cute-gradient-accent;
		border-radius: 50%;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.cat-ears {
		position: absolute;
		top: -20rpx;
		width: 100%;
		display: flex;
		justify-content: space-between;
		padding: 0 20rpx;
	}
	
	.ear {
		width: 30rpx;
		height: 30rpx;
		background: $cute-gradient-accent;
		border-radius: 50% 50% 0 0;
		
		&.left {
			transform: rotate(-30deg);
		}
		
		&.right {
			transform: rotate(30deg);
		}
	}
	
	.cat-eyes {
		display: flex;
		gap: 20rpx;
		margin-bottom: 15rpx;
	}
	
	.eye {
		width: 12rpx;
		height: 12rpx;
		background: $cute-text-inverse;
		border-radius: 50%;
	}
	
	.cat-nose {
		width: 8rpx;
		height: 6rpx;
		background: $cute-text-inverse;
		border-radius: 50%;
	}
	
	.empty-text {
		display: block;
		font-size: 32rpx;
		color: $cute-text-primary;
		font-weight: bold;
		margin-bottom: 15rpx;
	}
	
	.empty-desc {
		font-size: 26rpx;
		color: $cute-text-secondary;
	}
	
	/* 加载状态 */
	.loading-more {
		padding: 40rpx;
		text-align: center;
	}
	
	.loading-text {
		font-size: 26rpx;
		color: $cute-text-secondary;
	}
	
	.no-more {
		padding: 40rpx;
		text-align: center;
	}
	
	.no-more-text {
		font-size: 24rpx;
		color: $cute-text-tertiary;
	}
	
	/* 悬浮添加按钮 */
	.fab {
		position: fixed;
		bottom: 40rpx;
		right: 40rpx;
		width: 120rpx;
		height: 120rpx;
		background: $cute-gradient-primary;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 32rpx rgba(144, 238, 144, 0.4);
		transition: $cute-transition;
		z-index: 1000;
		
		&:active {
			transform: scale(0.9);
		}
	}
	
	.fab-icon {
		font-size: 48rpx;
		color: $cute-text-inverse;
		font-weight: bold;
	}
</style>
